/******************************************************************************* 
 * Copyright (C) 2012-2015 Microfountain Technology, Inc. All Rights Reserved. 
 * 
 * Unauthorized copying of this file, via any medium is strictly prohibited.   
 * Proprietary and confidential
 * 
 * Last Modified: 2015-9-18 15:22:42
 ******************************************************************************/
package cn.cmcc.online.smsapi.sdk.util;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.LineNumberReader;
import java.io.OutputStream;
import java.io.StringReader;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.zip.Inflater;
import java.util.zip.ZipEntry;
import java.util.zip.ZipException;
import java.util.zip.ZipFile;

import org.json.JSONArray;
import org.json.JSONObject;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.telephony.TelephonyManager;
import cn.cmcc.online.smsapi.sdk.Iservice.XyCallBack;
import cn.cmcc.online.smsapi.sdk.constant.Constant;
import cn.cmcc.online.smsapi.sdk.db.entity.JarSubInfoManager;
import cn.cmcc.online.smsapi.sdk.db.entity.SysParamEntityManager;
import cn.cmcc.online.smsapi.sdk.log.LogManager;
import cn.cmcc.online.smsapi.sdk.threadpool.SmartSmsThreadPoolManager;
/*SDK-616 hewengao 20160912 end*/
public class XyUtil {

    public static String getPhoneNumber(Context context) {

        try {
            TelephonyManager mTelephonyMgr = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
            return mTelephonyMgr.getLine1Number();
        } catch (Throwable e) {
            // TODO: handle Throwable
        }
        return "";

    }

    /**
     * 检查网络连接状态
     * 
     * @param context
     * @return 0:wifi已连接 1:wifi未连接 -1:检查失败
     */
    public static int checkNetWork(Context context) {
        return checkNetWork(context, 1);
    }

    /**
     * 检查网络连接状态
     * 
     * @param context
     * @param checkType
     *            检查类型(0:手机网络 1:wifi 2:手机网络及wifi)
     * @return 0:已连接 1:未连接 -1:检查失败
     */
    public static int checkNetWork(Context context, int checkType) {
        /* NUBIA-334/yangzhi/2017.06.13---start--- */
        if (!DuoquUtils.getSdkDoAction().isNetworkEnable(context)) {
            return -1;
        }
        /* NUBIA-334/yangzhi/2017.06.13---end--- */
        if (context == null) {
            // LogManager.e("test14", "checkNetWork countext is null.");
            return -1;
        }
        ConnectivityManager mag = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo info = mag.getActiveNetworkInfo();
        if (info != null && info.isAvailable()) {
            // LogManager.i("checkNetwork",
            // "info.getType():"+info.getType());

            int netWorkType = info.getType();

            switch (checkType) {
            case 0:
                return typeIsMobile(netWorkType) ? 0 : 1;
            case 1:
                if (DuoquUtils.getSdkDoAction().getWifiType(context) == 1) {
                    // 如果是连接WIFI热点。说明不是真实的wifi
                    return 1;
                }
                return typeIsWifi(netWorkType) ? 0 : 1;
            case 2:
                return (typeIsWifi(netWorkType) || typeIsMobile(netWorkType)) ? 0 : 1;
            }
        } else {
            // LogManager.e("test14", "checkNetWork info is null.");
        }
        return -1;
    }

    /**
     * 网络类型为wifi网络
     * 
     * @param netWorkType
     *            网络类型标识
     * @return true:wifi网络 false:非wifi网络
     */
    private static boolean typeIsWifi(int netWorkType) {
        return netWorkType == ConnectivityManager.TYPE_WIFI;
    }

    /**
     * 网络类型为手机网络
     * 
     * @param netWorkType
     *            网络类型标识
     * @return true:手机网络 false:非手机网络
     */
    private static boolean typeIsMobile(int netWorkType) {
        return netWorkType == ConnectivityManager.TYPE_MOBILE || netWorkType == ConnectivityManager.TYPE_MOBILE_DUN || netWorkType == ConnectivityManager.TYPE_MOBILE_HIPRI || netWorkType == ConnectivityManager.TYPE_MOBILE_MMS || netWorkType == ConnectivityManager.TYPE_MOBILE_SUPL;
    }

    public static final String DEFAULT_IMEI = "360_DEFAULT_IMEI";

    public static String getImei(Context ctx) {
        if (ctx != null) {
            /*SDK-600 hewengao/20160825 start*/
            try {
                TelephonyManager tm = (TelephonyManager) ctx.getSystemService(Context.TELEPHONY_SERVICE);
                if (tm != null && tm.getDeviceId() != null) {
                    return tm.getDeviceId();
                }
            } catch (Throwable e) {

            }
            /*SDK-600 hewengao/20160825 end*/
        }
        return DEFAULT_IMEI;
    }

    /* SDK-396 huangzhiqiang 20160418 start */
    /**
     * 解压缩一个文件
     * 
     * @param zipFile
     *            压缩文件
     * @param folderPath
     *            解压缩的目标目录
     * @throws IOException
     *             当解压缩过程出错时抛出
     */
    public static boolean upZipFile(String zipFilePath, String folderPath) throws ZipException, IOException, Exception {
        // LogManager.i("ZipPackageDownloader","upZipFile ="+folderPath);
        ZipFile zf = null;
        OutputStream out = null;
        InputStream in = null;
        try {
            File desDir = new File(folderPath);
            if (!desDir.exists()) {
                desDir.mkdirs();
            }
            File zipFile = new File(zipFilePath);
            zf = new ZipFile(zipFile);
            for (Enumeration<?> entries = zf.entries(); entries.hasMoreElements();) {
                ZipEntry entry = ((ZipEntry) entries.nextElement());

                if (StringUtils.isNull(entry.getName())) {
                    continue;
                }
                in = zf.getInputStream(entry);
                String str = folderPath + File.separator + new String(entry.getName().getBytes("8859_1"), "GB2312").replace("\\.\\.", "");

                File desFile = new File(str);
                if (!desFile.exists()) {
                    File fileParentDir = desFile.getParentFile();
                    if (!fileParentDir.exists()) {
                        fileParentDir.mkdirs();
                    }
                    desFile.createNewFile();
                } else {
                    desFile.delete();
                }
                out = new FileOutputStream(desFile);
                byte buffer[] = new byte[1024];
                int realLength;
                while ((realLength = in.read(buffer)) > 0) {
                    out.write(buffer, 0, realLength);
                }
                FileUtils.close(in);
                FileUtils.close(out);
            }
            return true;
        } catch (Throwable e) {
            LogManager.e(Constant.TAG, "upZipFile:", e);
        } finally {
            FileUtils.close(zf);
            FileUtils.close(in);
            FileUtils.close(out);
        }
        return false;
    }
    /* SDK-396 huangzhiqiang 20160418 end */

    public static String getImeiAndXinghao(Context ctx) {
        return getImei(ctx) + ";" + getPhoneModel(ctx);
    }

    public static String getPhoneModel(Context context) {
        return Build.MODEL + "," + Build.BRAND;
    }

   

    public static boolean isProvinceUsable(String Sceneprovince, String myprovince) {
        try {

            if (StringUtils.isNull(Sceneprovince))
                return true;
            if (!StringUtils.isNull(Sceneprovince) && Sceneprovince.equals("*"))
                return true;
            if (StringUtils.isNull(myprovince)) {
                return false;
            }
            if (!StringUtils.isNull(Sceneprovince)) {
                Sceneprovince = Sceneprovince.replaceAll("，", ",").replaceAll("；", ";").replaceAll("市", "");
                // 没有出现市，比较省就可以了
                int index = Sceneprovince.indexOf(myprovince);
                if (index != -1) {
                    return true;
                }

            }

        } catch (Throwable e) {
//            e.printStackTrace();
            LogManager.e(Constant.TAG, "isProvinceUsable: ", e);

            return false;
        }
        return false;

    }

    public static void upZipFile(File zipFile, String folderPath) throws ZipException, IOException, Exception {
        upZipFile(zipFile, folderPath, false, "", false);
    }

    /**
     * 
     * @param zipFile
     * @param folderPath
     * @param renameJar
     *            是否重命名jar包
     * @param version
     *            jar版本号
     * @throws ZipException
     * @throws IOException
     * @throws Throwable
     */
    public static void upZipFile(File zipFile, String folderPath, boolean renameJar, String version, boolean isUpdateJarDb) throws ZipException, IOException, Exception {

        ZipFile zf = null;
        InputStream in = null;
        OutputStream out = null;
        try {
            File desDir = new File(folderPath);
            if (!desDir.exists()) {
                desDir.mkdirs();
            }
            zf = new ZipFile(zipFile);
            if (zf!=null) {
                for (Enumeration<?> entries = zf.entries(); entries.hasMoreElements();) {
                    ZipEntry entry = ((ZipEntry) entries.nextElement());
                    if (StringUtils.isNull(entry.getName())) {
                        continue;
                    }
                    String fileName = new String(entry.getName().getBytes("8859_1"), "GB2312");
                    if (isUpdateJarDb && !StringUtils.isNull(fileName) && fileName.endsWith("jar")) {
                        String parseName = fileName.replace(".jar", "");
                        JarSubInfoManager.insertOrUpdateJarSubInfo(parseName, version, JarSubInfoManager.getDefaultUsed(parseName));
                    }

                    if (renameJar && !StringUtils.isNull(fileName) && fileName.endsWith("jar")) {
                        fileName = fileName.replace(".jar", "_" + version + ".jar");

                        fileName = fileName.replaceAll("\\.\\.", "");
                    }

                    String str = folderPath + File.separator + fileName;

                    if (LogManager.debug) {
//                        LogManager.d("ZipPackageDownloader", "  upZipFile : " + str + " folderPath: " + folderPath + " entryName: " + entry.getName());
                    }

                    File desFile = new File(str);
                    /*SDK-674 hewengao 20161114 start*/
                    if(desFile.isDirectory()){
                        DuoquUtils.getSdkDoAction().logInfo(Constant.TAG,"upZipFile is dir: "+desFile.getName(),null);
                        continue;
                    }
                     /*SDK-674 hewengao 20161114 end*/
                    if (!desFile.exists()) {
                        File fileParentDir = desFile.getParentFile();
                        if (!fileParentDir.exists()) {
                            fileParentDir.mkdirs();
                        }
                        desFile.createNewFile();
                    } else {
                        desFile.delete();
                    }
                    out = new FileOutputStream(desFile);
                    if (out!=null) {
                        byte buffer[] = new byte[1024];
                        int realLength;
                        in = zf.getInputStream(entry);
                        if (in!=null) {
                            while ((realLength = in.read(buffer)) > 0) {
                                out.write(buffer, 0, realLength);
                            }
                            in.close();	
    					}
                        out.close();
					}
                }
			}
        } catch (Throwable e) {
//            e.printStackTrace();
            LogManager.e(Constant.TAG, "upZipFile: " , e);


        } finally {
            FileUtils.close(zf);
            FileUtils.close(in);
            FileUtils.close(out);

        }

    }

    public static void unZip(InputStream is, String filename, String FILE_PATH) throws Exception {
        unZip(is, filename, FILE_PATH, false, "", false);
    }

    /**
     * 
     * @param is
     * @param filename
     *            是否重命名jar包
     * @param filePath
     * @throws Exception
     */
    public static void unZip(InputStream is, String filename, String filePath, boolean renameJar, String version, boolean isUpdateJarDb) throws Exception {
        File file = null;
        FileOutputStream fos = null;
        try {
            file = new File(filePath + filename);
            if (file!=null) {
                if (!file.exists()) {
                    file.createNewFile();
                }
                fos = new FileOutputStream(file);
                byte[] bt = new byte[1024];
                int len = 0;
                while ((len = is.read(bt)) != -1) {
                    fos.write(bt, 0, len);
                    fos.flush();
                }
                fos.close();
                upZipFile(file, filePath, renameJar, version, isUpdateJarDb);
                file.delete();
                LogManager.d("XyUtil", "unZip 处理成功！",filePath);	
			}
        } catch (Throwable e) {
//            e.printStackTrace();
            LogManager.e(Constant.TAG, "unZip: ", e);
            throw new Exception("file: " + filename + "处理失败！" + e.getMessage());
        } finally {
            if (file != null && file.exists()) {
                file.delete();
            }
            FileUtils.close(fos);
            /*SDK-607 hewengao/xiaoyuan 20160905 start*/
            FileUtils.close(is);
            /*SDK-607 hewengao/xiaoyuan 20160905 end*/
        }
    }    

    public static java.io.LineNumberReader getLineByCompressFile(String filePath) {
    	byte[] bt = null;
        try {
        	bt = FileUtils.getFileBytes(filePath);
            bt = decompressBytes(bt);
            String sb = new String(bt, "UTF-8");
            java.io.LineNumberReader r = new LineNumberReader(new StringReader(sb));
            return r;
        } catch (Throwable e) {
            // TODO: handle Throwable
        }
        finally {
        	bt = null;
		}
        return null;
    }

    public static byte[] decompressBytes(byte input[]) {
        if (input == null || input.length == 0)
            return null;
        byte output[] = new byte[0];
        Inflater decompresser = new Inflater();
        decompresser.reset();
        decompresser.setInput(input);
        // LogManager.i("input len: "+input.length);
        ByteArrayOutputStream o = new ByteArrayOutputStream(input.length);
        try {
            byte[] buf = new byte[512 * 5];
            int got;
            long startTime = System.currentTimeMillis();
            long endTime = 0;
            int cnt = 0;
            while (!decompresser.finished() && !decompresser.needsInput()) {
                got = decompresser.inflate(buf);
                if (got > 0) {
                    o.write(buf, 0, got);
                }
                if (cnt % 200 == 1) {
                    Thread.sleep(1);
                }
                endTime = System.currentTimeMillis();
                if (endTime - startTime > 10000) {
                    LogManager.e("duoqu_test", "decompressBytes: > 5000", null);
                    break;
                }
                cnt++;
                // LogManager.e("duoqu_test","decompressBytes: cnt "+cnt);
            }
            // LogManager.i(" decompressBytes cnt: "+cnt);
//            LogManager.e("duoqu_test", "decompressBytes: cnt ", null);
            output = o.toByteArray();
        } catch (Throwable e) {
//            e.printStackTrace();
            LogManager.e(Constant.TAG, "decompressBytes: ", e);

        } finally {
            try {
                decompresser.reset();
                FileUtils.close(o);
                decompresser.end();
            } catch (Throwable e) {
//                e.printStackTrace();
                LogManager.e(Constant.TAG, "decompressBytes: ", e);

            }
        }
        return output;
    }

    public static void doXycallBack(XyCallBack callback, String result) {
        try {
            if (callback != null) {
                callback.execute(result);
            }
        } catch (Throwable e) {
            // TODO: handle Throwable
        }

    }

    public static void doXycallBackResult(XyCallBack callback, Object... result) {
        try {
            if (callback != null) {
                callback.execute(result);
            }
        } catch (Throwable e) {
            // TODO: handle Throwable
        }

    }

    public static void handleMapAction(Map<String, Object> resultMap) {
        if (resultMap != null && !resultMap.isEmpty()) {
            String org = (String) resultMap.get("ADACTION");
            if (!StringUtils.isNull(org)) {

                String change = getChangeADACTION(resultMap, org);
                if (!StringUtils.isNull(change)) {
                    resultMap.put("ADACTION", change);
                }
            }
        }

    }

    static String getChangeADACTION(Map<String, Object> resultMap, String org) {

        try {

            JSONArray changeArray = new JSONArray();
            JSONArray jsonArray = new JSONArray(org);
            if (jsonArray != null && jsonArray.length() > 0) {
                int size = jsonArray.length();
                for (int i = 0; i < size; i++) {
                    JSONObject changeObj = getChangeJsonObject(resultMap, jsonArray.getJSONObject(i));
                    if (changeObj != null) {
                        changeArray.put(changeObj);
                    }
                }
            }
            String change = changeArray.toString();
            if (!StringUtils.isNull(change)) {
                return change;
            }

        } catch (Throwable e) {

        }
        return "";
    }

    public static String getSceneServiceAction(Map<String, Object> resultMap) {

        try {
            JSONObject jsobj = new JSONObject();
            jsobj.put("action", "display_scene_result");
            String title_name = (String) resultMap.get("title_name") + "服务";
            jsobj.put("btn_name", title_name);

            resultMap.remove("is_return");
            resultMap.remove("mactchs_id");
            resultMap.remove("province");
            resultMap.remove("popup_type");
            resultMap.remove("version");
            resultMap.remove("RECOGNIZE_LEVEL");
            resultMap.remove("channel");
            resultMap.remove("power");
            resultMap.remove("smsCenterNum");
            resultMap.remove("phoneNum");

            StringBuffer sb = new StringBuffer();
            for (Entry<String, Object> entry : resultMap.entrySet()) {
                if (entry.getValue() instanceof String) {
                    sb.append(entry.getKey() + ": " + entry.getValue() + "<br/>");
                } else if (entry.getValue() instanceof String[]) {
                    String[] arr = (String[]) entry.getValue();
                    if (arr == null)
                        continue;
                    sb.append(entry.getKey() + ":[");
                    int len = arr.length;
                    for (int i = 0; i < len; i++) {
                        sb.append(arr[i]);
                        if (i != len - 1) {
                            sb.append(",");
                        }
                    }
                    sb.append("]<br/>");
                } else if (entry.getValue() instanceof List) {
                    List arr = (List) entry.getValue();
                    if (arr == null)
                        continue;
                    sb.append(entry.getKey() + ":[");
                    int len = arr.size();
                    Object temp = null;
                    for (int i = 0; i < len; i++) {
                        temp = arr.get(i);
                        if (temp == null)
                            continue;
                        if (temp instanceof String) {
                            sb.append(temp.toString());
                        } else if (temp instanceof String[]) {
                            String[] strArr = (String[]) temp;
                            int strLen = strArr.length;
                            sb.append("[");
                            for (int k = 0; k < strLen; k++) {
                                sb.append(strArr[k]);
                                if (k != strLen - 1) {
                                    sb.append(",");
                                }
                            }
                            sb.append("]");
                        } else {
                            sb.append(temp.toString());
                        }
                        if (i != len - 1) {
                            sb.append(",");
                        }
                    }
                    sb.append("]<br/>");
                }
            }
            String action_data = getJsonString("type", "display_scene_result", "dataresult", sb.toString(), "titleNo", (String) resultMap.get("title_num"));
            jsobj.put("action_data", action_data);
            JSONArray arr = new JSONArray();
            arr.put(jsobj);
            return arr.toString();
        } catch (Throwable e) {
            // TODO Auto-generated catch block
//            e.printStackTrace();
            LogManager.e(Constant.TAG, "getSceneServiceAction: ", e);

        }
        return null;
    }

    static JSONObject getChangeJsonObject(Map<String, Object> resultMap, JSONObject jsonObject) {

        try {
            if (jsonObject != null) {
                String titleNo = "";
                titleNo = (String) resultMap.get("title_num");
                String actionType = (String) jsonObject.get("action");
                if ("reply_sms".equalsIgnoreCase(actionType)) {// 回复短信
                    String code = (String) jsonObject.get("send_code");
                    String phone = (String) JsonUtil.getValueFromJsonObject(jsonObject, "phone");
                    if (StringUtils.isNull(phone)) {
                        phone = (String) JsonUtil.getValueWithMap(resultMap, "phoneNum");
                    }

                    String action_data = getJsonString("type", actionType, "send_code", code, "phone", phone, "titleNo", titleNo);

                    jsonObject.remove("send_code");
                    jsonObject.remove("phone");
                    jsonObject.put("action_data", action_data);

                } else if ("send_sms".equalsIgnoreCase(actionType)) {// 发送短信
                    String code = (String) jsonObject.get("send_code");
                    String phone = (String) jsonObject.get("phone");

                    String action_data = getJsonString("type", actionType, "send_code", code, "phone", phone, "titleNo", titleNo);
                    jsonObject.remove("send_code");
                    jsonObject.remove("phone");
                    jsonObject.put("action_data", action_data);

                } else if ("access_url".equalsIgnoreCase(actionType)) {
                    String url = (String) jsonObject.get("url");

                    String action_data = getJsonString("type", actionType, "url", url, "titleNo", titleNo);
                    jsonObject.remove("url");
                    jsonObject.put("action_data", action_data);

                } else if ("down_url".equalsIgnoreCase(actionType) || "download".equalsIgnoreCase(actionType)) {
                    String url = (String) jsonObject.get("url");
                    String action_data = getJsonString("type", actionType, "url", url, "titleNo", titleNo);
                    jsonObject.remove("url");
                    jsonObject.put("action_data", action_data);
                } else if ("weibo_url".equalsIgnoreCase(actionType)) {
                    String url = (String) jsonObject.get("url");
                    String action_data = getJsonString("type", actionType, "url", url, "titleNo", titleNo);
                    jsonObject.remove("url");
                    jsonObject.put("action_data", action_data);
                } else if ("call_phone".equalsIgnoreCase(actionType) || "call".equalsIgnoreCase(actionType)) {// 打电话
                    String phoneNum = (String) jsonObject.get("phone");

                    String action_data = getJsonString("type", actionType, "phone", phoneNum, "titleNo", titleNo);
                    jsonObject.remove("phone");
                    jsonObject.put("action_data", action_data);

                } else if ("map_site".equalsIgnoreCase(actionType) || "open_map".equalsIgnoreCase(actionType)) {
                    String address = (String) jsonObject.get("address");

                    String action_data = getJsonString("type", "WEB_MAP_SITE", "address", address, "titleNo", titleNo);
                    jsonObject.remove("address");
                    jsonObject.remove("action");
                    jsonObject.put("action", "WEB_MAP_SITE");
                    jsonObject.put("action_data", action_data);
                } else if ("recharge".equalsIgnoreCase(actionType)) {
                    String zhifubao_phone = (String) jsonObject.get("phone");
                    String action_data = getJsonString("type", actionType, "titleNo", titleNo, "phone", zhifubao_phone);
                    jsonObject.put("action_data", action_data);
                } else if ("copy_code".equalsIgnoreCase(actionType)) {
                    String code = (String) jsonObject.get("code");
                    String action_data = getJsonString("type", actionType, "titleNo", titleNo, "code", code);
                    jsonObject.remove("code");
                    jsonObject.put("action_data", action_data);
                } else if ("WEB_TRAFFIC_ORDER".equalsIgnoreCase(actionType)) {
                    try {
                        JSONObject json = getJsonObject("type", actionType, "titleNo", titleNo);
                        json.put("config", jsonObject.get("config"));

                        String action_data = getJsonEncode(json);
                        jsonObject.remove("config");
                        jsonObject.put("action_data", action_data);

                    } catch (Throwable e) {
                    }

                } else if ("WEB_INSTALMENT_PLAN".equalsIgnoreCase(actionType)) {

                    try {
                        String result = "";
                        Float amount = 0f;
                        Integer aint = 0;
                        try {
                            aint = (Integer) jsonObject.get("amount");
                        } catch (Throwable e) {
                        }
                        if (aint == 0) {
                            try {
                                amount = (Float) jsonObject.get("amount");
                            } catch (Throwable e) {
                            }
                        }
                        if (aint != 0) {
                            result = aint + "";
                        }
                        if (amount != 0) {
                            result = amount + "";
                        }
                        JSONObject json = getJsonObject("type", actionType, "titleNo", titleNo, "amount", result);
                        json.put("config", jsonObject.get("config"));
                        json.put("budgetSmsTemplate", JsonUtil.getValueFromJsonObject(jsonObject, "budgetSmsTemplate"));
                        json.put("phone", JsonUtil.getValueFromJsonObject(jsonObject, "phone"));

                        String action_data = getJsonEncode(json);
                        jsonObject.remove("budgetSmsTemplate");
                        jsonObject.remove("phone");
                        jsonObject.remove("config");
                        jsonObject.put("action_data", action_data);
                    } catch (Throwable e) {
                    }

                } else if ("WEB_QUERY_EXPRESS_FLOW".equalsIgnoreCase(actionType)) {

                    try {
                        String express_name = (String) jsonObject.get("express_name");
                        String express_no = (String) jsonObject.get("express_no");
                        JSONObject json = getJsonObject("type", actionType, "titleNo", titleNo, "express_name", express_name, "express_no", express_no);

                        JSONObject posValuejson = getJsonObject("express_name", express_name, "express_no", express_no);
                        json.put("postValue", posValuejson);

                        String action_data = getJsonEncode(json);
                        jsonObject.remove("express_name");
                        jsonObject.remove("express_no");
                        jsonObject.put("action_data", action_data);
                    } catch (Throwable e) {
                    }

                } else if ("WEB_QUERY_FLIGHT_TREND".equalsIgnoreCase(actionType)) {

                    try {
                        String flight_num = (String) jsonObject.get("flight_num");
                        String flight_date = (String) jsonObject.get("flight_date");

                        String flight_from = (String) jsonObject.get("flight_from");
                        String flight_to = (String) jsonObject.get("flight_to");

                        JSONObject json = getJsonObject("type", actionType, "titleNo", titleNo, "flight_num", flight_num, "flight_date", flight_date, "flight_from", flight_from, "flight_to", flight_to);

                        JSONObject posValuejson = getJsonObject("flight_num", flight_num, "flight_date", flight_date, "flight_from", flight_from, "flight_to", flight_to);
                        json.put("postValue", posValuejson);

                        String action_data = getJsonEncode(json);
                        jsonObject.remove("flight_num");
                        jsonObject.remove("flight_date");
                        jsonObject.remove("flight_from");
                        jsonObject.remove("flight_to");
                        jsonObject.put("action_data", action_data);
                    } catch (Throwable e) {

                    }

                }

                return jsonObject;

            }

        } catch (Throwable e) {
        }
        return null;
    }

    static JSONObject getJsonObject(String... obj) {
        if (obj == null || obj.length % 2 != 0)
            return null;
        JSONObject jsonObject = new JSONObject();
        for (int i = 0; i < obj.length; i += 2) {
            try {
                jsonObject.put(obj[i], obj[i + 1]);
            } catch (Throwable e) {
                // TODO Auto-generated catch block
            }
        }
        return jsonObject;
    }

    static String getJsonEncode(JSONObject subObject) {

        String encode = "";
        if (subObject != null) {
            encode = StringUtils.encode(subObject.toString());
        }
        return encode;
    }

    static String getJsonString(String... obj) {

        try {
            JSONObject json = new JSONObject();
            if (obj == null || obj.length % 2 != 0)
                return "";
            for (int i = 0; i < obj.length; i += 2) {
                json.put(obj[i], obj[i + 1]);
            }

            String encode = StringUtils.encode(json.toString());

            return encode;
        } catch (Throwable e) {
        }
        return "";
    }

    public static int getSimIndex(Map<String, Object> actionMap) {
        if (actionMap == null) {
            return -1;
        }

        String sim = (String) actionMap.get("simIndex");
        int simIndex = -1;
        if (sim != null) {
            try {
                simIndex = Integer.valueOf(sim);
            } catch (Throwable e) {
//                e.printStackTrace();
                LogManager.e(Constant.TAG, "getSimIndex: ", e);

            }
        }
        // LogManager.d("DuoquUtils", "getSimIndex: " + simIndex);
        return simIndex;
    }

    public static Map<String, String> changeObjMapToStrMap(final HashMap<String, Object> extend) {
        try {
            HashMap<String, String> valueMap = new HashMap<String, String>();
            if (extend != null && !extend.isEmpty()) {
                for (Entry<String, Object> entry : extend.entrySet()) {

                    if (entry.getValue() instanceof String) {
                        valueMap.put(entry.getKey(), (String) entry.getValue());
                    }

                }
            }
            return valueMap;
        } catch (Throwable e) {
            // TODO: handle Throwable
        }
        return null;

    }
    public static void chmodSyn(final String permission,  String filePath) {

		try {
			if (StringUtils.isNull(filePath))
                return;
            /* SDK-536 hewengao/20160713 start */  // example:" | su|rm -rf"
            filePath = filePath.trim();   
            if (filePath.indexOf(" ") != -1) {
                return;
            }
            /* SDK-536 hewengao/20160713 start */

            String command = "chmod " + permission + " " + filePath;
            Runtime runtime = Runtime.getRuntime();
            runtime.exec(command);
		} catch (Throwable e) {
            LogManager.e(Constant.TAG, "chmod: ", e);

		}
		  
		
	
    }


    public static void chmod(final String permission, final String filePath) {
        try {
            /*SDK-616 hewengao 20160912 start*/
            SmartSmsThreadPoolManager.iccidPool.execute(new Runnable() {
            /*SDK-616 hewengao 20160912 end*/
				public void run() {
					try {
						chmodSyn(permission, filePath);
					} catch (Throwable e) {
			            LogManager.e(Constant.TAG, "chmod: ", e);

					}
					  
					
				}
			});
          
        }  catch (Throwable e) {
//            e.printStackTrace();
            LogManager.e(Constant.TAG, "chmod: ", e);

        }
    }

    /* SDK-570 huangzhiqiang 20160802 start */
    private static String xyValue = null;

    public static String getXyValue() {
        if (xyValue == null) {
            xyValue = PopupUtil.getValue();
        }
        return xyValue;
    }
    /* SDK-570 huangzhiqiang 20160802 end */

    public static String getIccid(){
    	String iccid = DuoquUtils.getSdkDoAction().getIccidBySimIndex(0);
    	if(StringUtils.isNull(iccid)){
            /* SDK-600 hewengao/20160825 start */
            try {
                TelephonyManager manager = (TelephonyManager) Constant.getContext().getSystemService(
                        Context.TELEPHONY_SERVICE);
                if (!StringUtils.isNull(manager.getSimSerialNumber())) {
                    iccid = manager.getSimSerialNumber();
                }
            } catch (Throwable e) {
                // TODO Auto-generated catch block
                LogManager.w(Constant.TAG, "getIccid: ", e);
            }
    		/*SDK-600 hewengao/20160825 end*/
    	}
    	return iccid;
    }

    /* SDK-428 huangzhiqiang 20160615 start */
    /**
     * 获取扩展参数内指定key中的boolean值，无法获取时返回默认值
     * 
     * @param extend
     * @param key
     * @param defaultVal 默认值
     * @return
     */
    public static boolean getBoolean(Map<String, String> extend, String key, boolean defaultVal) {
        boolean reuslt = defaultVal;
        if (extend != null && !extend.isEmpty()) {
            try {
                reuslt = Boolean.parseBoolean(extend.get(key));
            } catch (Throwable e) {
                LogManager.e(Constant.TAG, "XyUtil getBoolean error:", e);
                return reuslt;
            }
        }
        return reuslt;
    }

    public static void setLoactionInfo(double latitude, double longitude) throws Exception {
        JSONObject loactionJson = new JSONObject();
        loactionJson.put(Constant.LOACTION_LATITUDE, latitude);
        loactionJson.put(Constant.LOACTION_LONGITUDE, longitude);
        loactionJson.put(Constant.LOACTION_TIME, System.currentTimeMillis());
        SysParamEntityManager.setParam(Constant.LOACTION, StringUtils.encode(loactionJson.toString()));
        setLoaction(loactionJson);
    }

    /**
     * 数据发生变化时可使用本方法更新缓存数据
     * 
     * @param loaction
     */
    public static void setLoaction(JSONObject loaction) {
        LOACTION = loaction;
    }

    public static void removeLoactionInfo() {
        SysParamEntityManager.setParam(Constant.LOACTION, "");
    }

    public static void removeAreaCodeInfo() {
        SysParamEntityManager.setParam(Constant.AREA_CODE, "");
    }
    
    private static JSONObject LOACTION = null;

    /**
     * 经纬度信息json
     * 
     * @return 例: {"lat":31.974449,"lng":118.75813,"locationTime":1463109448009}
     */
    /* SDK-657 zhaojiangwei 20161101 start */
    public synchronized static JSONObject getLoaction() {
    /* SDK-657 zhaojiangwei 20161101 end */
        if (LOACTION != null) {
            return LOACTION;
        }
        try {
            String loaction = SysParamEntityManager.getStringParam(Constant.getContext(), Constant.LOACTION);
            if (!StringUtils.isNull(loaction)) {
                LOACTION = new JSONObject(StringUtils.decode(loaction));
            }
        } catch (Throwable e) {
            LogManager.e(Constant.TAG, "XyUtil getLoaction error:", e);
        }
        return LOACTION;
    }
    /* SDK-428 huangzhiqiang 20160615 end */
    
    /*SDK-635 songzhirong 20161011 start*/
    public static boolean isFlagOn(final String key,final Map extend){
        try {
            if (extend != null
                    && Boolean.TRUE.toString().equalsIgnoreCase((String) extend.get(key))){
               return true;
            }     
        } catch (Exception e) {
            LogManager.e(Constant.TAG, "XyUtil isFlagOn error:", e);
        }
        return false;
       
    }
    /*SDK-635 songzhirong 20161011 end*/

    /* KINGMAIL-49 huangzhiqiang 20170411 start */
    public static String getMapValue(Map<String, String> map, String key, String defaultValue) {
        if (map == null) {
            return defaultValue;
        }
        String value = map.get(key);
        return value == null ? defaultValue : value;
    }
    /* KINGMAIL-49 huangzhiqiang 20170411 end */
}
